﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json;

namespace Main.Packets
{
    public class DataPacket : Packet
    {
        private const int MAX_BYTES = 128;

        private string data;

        private DataPacket(byte numeroConnexion, PacketType type, string data) : base(numeroConnexion, type)
        {
            this.data = data;
        }

        [JsonProperty(Order = 15)]
        public string Data
        {
            get { return data; }
            set { data = value; }
        }

        public static List<DataPacket> CreateDataPackets(byte numeroConnexion, int pr, int ps, string data)
        {
            int length;
            bool hasNext;
            DataPacket packet;
            List<DataPacket> packets = new List<DataPacket>();

            for (int i = 0; i < data.Length; i += MAX_BYTES)
            {
                hasNext = ((i + MAX_BYTES) < data.Length);

                length = Math.Min(data.Length - i, MAX_BYTES);

                packet = new DataPacket(numeroConnexion, PacketType.CreateTypeForDataPacket(pr, hasNext, ps), data.Substring(i, length));

                packets.Add(packet);
            }

            return packets;
        }

        public static DataPacket CreateDataPacket(string str)
        {
            return JsonConvert.DeserializeObject<DataPacket>(str) as DataPacket;
        }

        public override void WriteJson(System.IO.StreamWriter sw)
        {
            sw.WriteLine(JsonConvert.SerializeObject(this));
        }
    }
}
